import React, { ReactElement, useContext, useEffect, useMemo } from 'react';
import { DeviceEventEmitter, Text, View } from 'react-native';

import styles from './style';
import { Store } from '../../reducer';
import Button from '../../../../components/Button';
import { setShowLock } from '../../actions';
import { FacePositionChangeData } from '../../types';
import { CLASS_ROOM_EVENT_FACE_POSITION_CHANGE, emitNoFace } from '../../event';
import { ClassRoomType, PPTType, RoundType, UserRole } from '../../constant';
import { getUserInfo } from '../../../../store/user';
import tracker from '../../../../util/actionTracker';
import { lockFace, unLockFace } from '../../../../constant/events';

const MAX_LOCK_SCREEN_TIME = 30 * 1000;

export default (): ReactElement => {
  const { state } = useContext(Store);
  const { showLock, showSignIn, showPrepare, type, currentPPT, lesson } = state;
  const { lessonId } = lesson;
  const { round: currentRound, type: pptType } = currentPPT;
  let isRestVideo = false;
  const isProblem = pptType === PPTType.Problem;

  if (currentRound) {
    const { roundInfoVideo, roundType } = currentRound;
    isRestVideo =
      roundType === RoundType.Video && roundInfoVideo && roundInfoVideo.isRest;
  }
  const isVod = type === ClassRoomType.Vod;

  const { role } = getUserInfo();
  const isParent = role === UserRole.Parent;

  const canNotGetFacePosition =
    showLock ||
    showSignIn ||
    showPrepare ||
    isVod ||
    isRestVideo ||
    isProblem ||
    isParent;

  useEffect((): (() => void) => {
    if (canNotGetFacePosition) return (): void => {};

    let timer: NodeJS.Timer | null = null;
    let noFaceTimer: NodeJS.Timer | null = null;
    const clearTimer = (): void => {
      if (timer) {
        clearTimeout(timer);
        timer = null;
      }
      if (noFaceTimer) {
        clearInterval(noFaceTimer);
        noFaceTimer = null;
      }
      emitNoFace({ time: -100 });
    };
    const subscription = DeviceEventEmitter.addListener(
      CLASS_ROOM_EVENT_FACE_POSITION_CHANGE,
      (data: FacePositionChangeData): void => {
        const { faceNumber } = data;
        if (faceNumber === 0 && !timer) {
          emitNoFace({ time: MAX_LOCK_SCREEN_TIME / 1000 });
          let time = MAX_LOCK_SCREEN_TIME / 1000;
          noFaceTimer = setInterval((): void => {
            time -= 1;
            emitNoFace({ time });
          }, 1000);
          timer = setTimeout((): void => {
            tracker.reportAction(lockFace, {
              objectId: lessonId
            });
            setShowLock(true);
            clearTimer();
          }, MAX_LOCK_SCREEN_TIME);
        } else if (faceNumber > 0) {
          clearTimer();
        }
      }
    );
    return (): void => {
      clearTimer();
      if (subscription) {
        subscription.remove();
      }
    };
  }, [
    canNotGetFacePosition,
    lessonId,
    showLock,
    showPrepare,
    showSignIn,
    type
  ]);

  return useMemo((): ReactElement => {
    if (!showLock) return <View />;

    return (
      <View style={styles.container}>
        <Text style={styles.lock}>教室已被锁定</Text>
        <Text style={styles.desc}>为保证学习效果，请全程露脸</Text>
        <Button
          style={styles.know}
          textStyle={styles.knowDesc}
          text="知道啦"
          onPress={(): void => {
            tracker.reportAction(unLockFace, {
              objectId: lessonId
            });
            setShowLock(false);
          }}
        />
      </View>
    );
  }, [lessonId, showLock]);
};
